package cms.api.solr.index.service;

import cms.api.framework.search.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;

/**
 * 索引服务实现类
 *
 * @author heyingcheng
 * @email heyingcheng@ctvit.com.cn
 * @date 2019/6/29 18:00
 */
@Slf4j
public abstract class BaseIndexServiceImpl implements IndexService {

    private final Supplier<String> DEFAULT_DOC_ID_GENERATOR = () -> UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    private Supplier<String> globalDocIdGenerator = DEFAULT_DOC_ID_GENERATOR;
    private final Map<String, Supplier<String>> DOC_ID_GENERATORS = new HashMap<>(16);

    @Override
    public void configDocIdGenerator4Type(String index, String type, Supplier<String> supplier) {
        this.DOC_ID_GENERATORS.put(getGeneratorKey4Index(index), supplier);
    }

    @Override
    public void configDocIdGenertor4Index(String index, Supplier<String> supplier) {
        this.DOC_ID_GENERATORS.put(getGeneratorKey4Index(index), supplier);
    }

    @Override
    public void configGlobalDocIdGenerator(Supplier<String> supplier) {
        if (StringUtils.isNotBlank(supplier.get())) {
            this.globalDocIdGenerator = supplier;
        }
    }

    protected String generateDocId(final String key) {
        if (this.DOC_ID_GENERATORS.containsKey(key)) {
            return this.DOC_ID_GENERATORS.get(key).get();
        }
        Supplier<String> supplier = this.DOC_ID_GENERATORS.putIfAbsent(key, this.globalDocIdGenerator);
        return supplier.get();
    }

    protected String getGeneratorKey4Index(String index) {
        return String.format("IDX:{%s}", index);
    }

}
